package upload

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils"
	"mime/multipart"
	"strings"
)

var AliyunOss = new(aliyunOss)

type aliyunOss struct{}

// 上传
func (p aliyunOss) Upload(file *multipart.FileHeader, key string) string {
	isCname := strings.Contains(global.CONF.AliyunOSS.Endpoint, "aliyuncs.com")
	bucket, err := p.NewBucket(isCname)
	if err != nil {
		panic(err)
	}

	f, openError := file.Open()
	if openError != nil {
		panic(openError)
	}
	defer f.Close()

	err = bucket.PutObject(strings.TrimLeft(key, "/"), f)
	if err != nil {
		panic(err)
	}
	var fileName string
	if isCname {
		fileName = utils.GetEndPoint(global.CONF.AliyunOSS.Endpoint) + key
	} else {
		fileName = global.CONF.AliyunOSS.Endpoint + key
	}
	return fileName
}

func (p aliyunOss) NewBucket(isCname bool) (*oss.Bucket, error) {
	client, err := oss.New(global.CONF.AliyunOSS.Endpoint, global.CONF.AliyunOSS.AccessKeyId, global.CONF.AliyunOSS.AccessKeySecret, oss.UseCname(!isCname))
	if err != nil {
		return nil, err
	}
	bucket, err := client.Bucket(global.CONF.AliyunOSS.BucketName)
	if err != nil {
		return nil, err
	}
	return bucket, nil
}

// 删除图片
func (p aliyunOss) DeleteFile(key string) bool {
	bucket, err := p.NewBucket(false)
	if err != nil {
		panic(err)
	}
	err = bucket.DeleteObject(key)
	if err != nil {
		panic(err)
	}
	return true
}
